######################
#  Replication code for 'Mediating the Electoral Connection', forthcoming in the JOP
#  John Henderson and John Brooks
#  12/7/2015    
######################    

# tableV-margin.R
#  :: produces a first stage results using unnormalized rain instruments and vote margin outcomes

rm(list=ls())
setwd('~/Dropbox/rainReplication')

# loop over data and fixed effects specifications 
for(fes.type in 2:3){ 
non.missings = 4

source('prelimMain.R')   

#detach(covs) 
# ANALYSIS

rain_day1_prev=rain_data$rain_day1[rain_data$prior_obs]
rain_weekend1_prev=rain_data$rain_weekend1[rain_data$prior_obs]
rain_day1_prev_prv=rain_data$rain_day1[rain_data$prior_obs][rain_data$prior_obs]
rain_weekend1_prev_prv=rain_data$rain_weekend1[rain_data$prior_obs][rain_data$prior_obs]                                                                
                                                                                         
covs$rain_day1=rain_data$rain_day1
covs$rain_weekend1=rain_data$rain_weekend1

covs$rain_day1_prev=rain_day1_prev                     
covs$rain_day1_prev_prv=rain_day1_prev_prv
covs$rain_weekend1_prev=rain_weekend1_prev
covs$rain_weekend1_prev_prv=rain_weekend1_prev_prv

main_fstage1_fe=lm(dose ~ as.factor(fe_id_num)+d_inc+
	extremist + dist_prev + midterm + pres_party + black + construction + educ + 
	minc + farmer + forborn + gvtwkr + manuf + pop + unempld + 
	urban + retail + sos + gov + comp_cq + redistricted + turnout_prv +
	dose_prv + vote_prv + rain_day1+rain_day1_prev+rain_day1_prev_prv, subset=full,data=covs)       
  
main_fstage2_fe=lm(dose ~ as.factor(fe_id_num)+d_inc+
	extremist + dist_prev + midterm + pres_party + black + construction + educ + 
	minc + farmer + forborn + gvtwkr + manuf + pop + unempld + 
	urban + retail + sos + gov + comp_cq + redistricted + turnout_prv +
	dose_prv + vote_prv + rain_weekend1+rain_weekend1_prev+rain_weekend1_prev_prv, subset=full,data=covs)	    
        
main_fstage1_fe_sum=summary(main_fstage1_fe)
main_fstage2_fe_sum=summary(main_fstage2_fe)

main_fstage1_fe_sumcl=coeftest.cluster(covs[full,],main_fstage1_fe,cluster1='as.factor(fe_id_num)')
main_fstage2_fe_sumcl=coeftest.cluster(covs[full,],main_fstage2_fe,cluster1='as.factor(fe_id_num)')

save(
main_fstage1_fe,
main_fstage2_fe,
main_fstage1_fe_sum,
main_fstage2_fe_sum,
main_fstage1_fe_sumcl,
main_fstage2_fe_sumcl,
file=paste('robustness/tableV_margin-',non.missings,'_',fes.type,'.Rdata',sep=''))      

rm(
main_fstage1_fe,
main_fstage2_fe,
main_fstage1_fe_sum,
main_fstage2_fe_sum,
main_fstage1_fe_sumcl,
main_fstage2_fe_sumcl
)

}      

# END